import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Question MinioUtil
 * @Date 2023/4/17 14:10
 * @Solution
 */
public class MinioUtil {
    private String host="43.138.177.200";
    private Integer port=9000;
    private boolean ssl=false;
    private String accessKey="roches";
    private String secretKey="sean760121";
    private String bucketName="usmusic";

    private MinioClient minioClient;
    private Map<String,String> contentType;
    public MinioUtil() {
        minioClient= MinioClient.builder()
                .endpoint(host,port,ssl)
                .credentials(accessKey,secretKey)
                .build();
        contentType=new HashMap<String,String>();
        contentType.put("png","image/png");
    }
    public void put(String key, InputStream is,long size) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        PutObjectArgs args= PutObjectArgs.builder()
                .bucket(bucketName)
                .object(key)
                .stream(is,size,-1)
                .contentType(getContentType(key))
                .build();
        minioClient.putObject(args);
    }

    public boolean isEmpty(String str) {
        return str==null||str.length()==0;
    }

    public String getExt(String filename) {
        if(isEmpty(filename)) {
            return "";
        }
        String name=filename.substring(filename.lastIndexOf("/")+1);
        if(name.contains("?")) {
            name=name.substring(0,name.indexOf("?"));
        }
        if(name.lastIndexOf(".")>-1) {
            return name.substring(name.lastIndexOf(".")+1);
        }
        return "";
    }

    public String  getContentType(String key) {
        String ext=getExt(key);
        if(contentType.containsKey(ext)) {
            return contentType.get(ext);
        }
        return "application/octet-stream";
    }
}
